package io.arukas.domain;

import io.arukas.domain.audit.DateAudit;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA. <br/>
 * Author: YuXian Niu <br/>
 * Email: niuyuxian@163.com <br/>
 * Create: 2021-08-15 21:43 <br/>
 */
@Data
@Entity
@Table(name = "sys_admin")
@EqualsAndHashCode(callSuper = true)
public class SysAdmin extends DateAudit implements UserDetails {

    // 用户名
    @Column(unique = true)
    private String username;

    // 密码
    private String password;

    // 注册状态
    private Integer state;

    @ManyToMany
    @JoinTable(name = "sys_admin_roles",
            joinColumns = {@JoinColumn(name = "user_id",
                    foreignKey = @ForeignKey(name = "none"))},
            inverseJoinColumns = {@JoinColumn(name = "role_id",
                    foreignKey = @ForeignKey(name = "none"))}
    )
    private Set<SysRole> roles = new HashSet<>();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList();
        List<String> collect = roles.stream().map(SysRole::getName).collect(Collectors.toList());
        collect.forEach(role -> {
            authorityList.add(new SimpleGrantedAuthority(role));
        });
        return authorityList;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}